<?php

namespace App\Http\Controllers\Test;

use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Service\Curl;
use App\Service\Dir;
use Illuminate\Support\Env;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;


class BigDataController extends Controller
{
    // ajax 保存远程的sql数据到本地
    public function initialize()
    {
        parent::initialize();
    }

    // 其他数据库链接
    public function other(){
        Config::set("database.connections.MysqL", [
            "host" => "...",
            "database" => "...",
            "username" => "...",
            "password" => "..."
        ]);

        //确保数据库重新连接了
        DB::reconnect('mysql');

    }

    // ajax 保存远程的sql数据到本地
    public function save()
    {
        set_time_limit(0);

        $table  = $this->getData('table');
        $page   = $this->getData('page');
        $number = 100;
        $table  = 0 === strpos($table, 'tp_') ? $table : 'tp_'.$table;
        $url    = 'http://api.ctsnews.com/v2/database/dbfile';
        $url    = 'http://newapi.caitongnews.com/v2/database/dbfile';
        $post   = ['table' => $table, 'page' => $page, 'number' => $number];

        // 采集数据
        $curl = new Curl();
        $res  = $curl->url($url)->post($post)->request();
        $res  = json_decode($res, true);

        // 如果返回错误
        if(empty($res)){
            return $this->success(['is_next' => 0]);
        }

        // 获取备份地址
        $ds      = DIRECTORY_SEPARATOR;
        $sqlPath = 'bak'.$ds.'sql'.$ds;
        $sqlPath = base_path($sqlPath);
        if(!is_dir($sqlPath)){
            (new Dir())->makeDir($sqlPath);
        }

        // 如果有数据 则保存数据
        // 如果返回数据少于1000条 则不在采集
        $list    = $res['data'];
        $cline   = chr(10);
        $is_next = 0;
        //$is_next = count($list) >= $number ? 1 : 0;
        $bak_sql = "-- ----------------------------".$cline;
        $bak_sql .= "-- Records for `".$table."`".$cline;
        $bak_sql .= "-- ----------------------------".$cline;
        if($list){
            // 保存在数据库中
            foreach($list as $key => $row){
                if(empty($is_next)){
                    $is_next = $row['id'] > 1874709 ? 0 : 1;
                }

                // 开始
                $make_sql = '';
                if($key % 50 == 0){
                    $do_sql = '';
                }
                foreach($row as $_val){
                    if(!isset($_val)){
                        $make_sql .= " NULL,";
                    } else{
                        $_val     = is_numeric($_val) ? $_val : ($_val == '' ? $_val : addslashes($_val));
                        $make_sql .= " '".$_val."',";
                    }
                }

                $make_sql   = substr($make_sql, 0, -1); ## 取消最后一个逗号
                $insert_sql = "INSERT INTO `$table` VALUES   ( $make_sql );".$cline;
                $bak_sql    .= $insert_sql;
                if($key % 50 == 49){
                    $do_sql .= "( $make_sql )";
                    $do_sql = "INSERT INTO `$table` VALUES    $do_sql ;".$cline;
                    // 保存到数据库中
                    //DB::connection('bigdata')->table('archive')->insert($row);
                    DB::connection('bigdata')->insert($do_sql);
                } else{
                    $do_sql .= "( $make_sql ),";
                }
            }

            // 保存在文件中
            $bak_sql .= "-- ----------------------------".$cline.$cline.$cline;

            ## 整理数据，生成统一文件
            $filename = $sqlPath.$table.".sql";
            if(is_file($filename)){
                if($page <= 1){
                    file_put_contents($filename, $bak_sql);
                } else{
                    file_put_contents($filename, $bak_sql, FILE_APPEND);
                }
            } else{
                file_put_contents($filename, $bak_sql);
            }
        }

        return $this->success(['is_next' => $is_next]);
    }

    // 自动翻页
    // http://www.mxsnews.com/test/big-data/page
    public function page()
    {
        $table = 'archive';
        $page   = $this->getData('page',1);

        // html
        $_host = Env::get('STYLE_HOST');
        $html  = '<script src="'.$_host.'/lib/jquery/jquery.min.js"></script>';
        $html  .= '<style>#show{font-size: 64px;color: red;}</style>';
        $html  .= '<h1>采集数据保存到本地</h1>';
        $html  .= '<h2>保存数据库文件位置：D:\phpSite\slcm\mxsnews\bak\sql</h2>';
        $html  .= '<div id="show">采集数据表，第1页</div>';

        // ajax 自动下一页
        $js = "
<script>
// 执行
caiji('".$table."', '".$page."');

// 自动采集下一页
function caiji(table, page) {
    console.log('执行采集', page);
    let url ='/test/big-data/save';
    $.ajax({
        type: 'get',
        url: url,
        // data: 'name=zhangsan&age=20'
        data: {table:table,page: page},
        contentType: 'application/json',
        // contentType: 'application/x-www-form-urlencoded',
        // 这个方法在请求发送前调用，可以用来做表单校验、用来做请求等待动画的调用
        /*beforeSend: function () {
            // 返回false是取消发送
            return false
        },*/
        // 会自动帮我们把返回的数据根据响应头设置的类型进行转换好（也就是会自动转成json对象）
        success: function (res) {
            console.log('采集结果', res)
            let is_next = res.data.is_next;
            let next_page = parseInt(page) + 1;
            if(is_next){
                $('#show').text('采集数据表' + table + '，第' + next_page + '页');
                setTimeout(\"caiji('\" + table + \"','\" + next_page + \"')\", 500);
            }else{
                $('#show').text('采集数据表' + table + '，结束！');
            }
        },
        // xhr是ajax对象
        error: function (xhr) {
        }
    });
}
</script>";

        echo $html.$js;
    }
}


